import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:toolbox/manager/hive/hiveHelper.dart';
import 'package:toolbox/page/browser/component/tool_bottom_sheet.dart';
import 'package:toolbox/page/home/home_logic.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../manager/tools.dart';
import 'browser_state.dart';

class BrowserLogic extends GetxController {
  final BrowserState state = BrowserState();

  @override
  void onInit() {
    super.onInit();
    state.isStar.listen((bool value) {
      updateTitle();
    });
    state.currentWebsiteFetch.listen((_) {
      updateTitle();
    });
    state.currentUrl.listen((_) {
      updateTitle();
    });
    state.controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            print('progress:$progress');
            state.progress.value = progress;
          },
          onPageFinished: (String url) {
            print('PageFinished:$url');
          },
          onPageStarted: (String url) async {
            print('onPageStarted');
            print('onPageStarted:$url');
            /// [onUrlChange]在安卓每次刷新都调用,使用[AndroidUrlChange]太麻烦
            /// 改为手动判断是否是刷新页面或者回到主页
            /// webHomePage重定向前后的url都需要比较
            state.currentWebsiteFetch.value = await fetchWebsiteInfo(url, fromCatch: false);
            if (url != state.currentUrl.value
                && url != HiveHelper.instance.webHomePageUrl
                && url != HiveHelper.instance.findWebsiteInfoFetchByUrl(HiveHelper.instance.webHomePageUrl)?.finalUrl
            ) {
              print('change to: $url');
              HiveHelper.instance.addWebHistory(url);
            }
            /// ————END
            state.currentUrl.value = state.currentWebsiteFetch.value?.finalUrl ?? url;
            checkStar();
            checkCanGoBackOrForward();
          },
        ),
      );
    loadWeb();
  }

  void updateTitle() {
    if (Get.isRegistered<HomeLogic>()) {
      Get.find<HomeLogic>()
        ..state.editWebTitle.value = false
        ..update();
    }
  }

  Future<void> loadWeb({String? url}) async {
    if (url == null || url.isEmpty) {
      url = HiveHelper.instance.webHomePageUrl;
    }
    if (!url.startsWith('https://')) {
      url = 'https://$url';
    }
    await state.controller.loadRequest(Uri.parse(url));
  }

  Future<void> starWeb() async {
    final url = await state.controller.currentUrl();
    if (url == null) {return;}
    String? starUrl = hasStarUrl(url);
    if (starUrl != null) {
      HiveHelper.instance.deleteWebStar(starUrl);
    } else {
      HiveHelper.instance.addWebStar(url);
    }
    checkStar();
  }

  Future<void> checkStar() async {
    final url = await state.controller.currentUrl();
    if (url == null) {
      state.isStar.value = false;
      return;
    }
    state.isStar.value = hasStarUrl(url) != null;
  }

  Future<void> checkCanGoBackOrForward() async {
    state.canGoBack.value = await state.controller.canGoBack();
    state.canGoForward.value = await state.controller.canGoForward();
  }

  Future<bool> goBack() async {
    try {
      if (await state.controller.canGoBack()) {
        await state.controller.goBack();
        return true;
      }
    } catch (e) {
      print(e);
    }

    return false;
  }

  Future<bool> goForward() async {
    try {
      if (await state.controller.canGoForward()) {
        await state.controller.goForward();
        return true;
      }
    } catch (e) {
      print(e);
    }

    return false;
  }

  Future<void> goHomePage() async {
    loadWeb();
  }

  Future<void> reload() async {
    await state.controller.reload();
  }

  void onTapBookMark(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      elevation: 0,
      isDismissible: true,
      builder: (context) => ToolsBottomSheet(),
    );
  }

  void setHomePage(String url) {
    HiveHelper.instance.webHomePageUrl = url;
  }
}
